﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.TextEditor.Document;

namespace tiDE.CodeFolding
{
    public class AxeFolding : IFoldingStrategy
    {
        public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInformation)
        {
            List<FoldMarker> foldMarkers = new List<FoldMarker>();
            Stack<FoldEntry> entries = new Stack<FoldEntry>();
            string[] Lines = document.TextContent.Replace("\r", "").Split('\n');
            int lineNumber = 0;
            if (Lines.Length == 1)
                return foldMarkers;
            foreach (string Line in Lines)
            {
                string line = Line.Trim();
                FoldEntry entry = null;
                if (line.StartsWith("While ") || line.StartsWith("For(") || line.StartsWith("Repeat "))
                {
                    entry = new FoldEntry();
                    entry.Line = lineNumber;
                    entry.Index = Line.Length;
                }
                if (line.StartsWith("If ") || line.StartsWith("!If "))
                {
                    entry = new FoldEntry();
                    entry.Line = lineNumber;
                    entry.Index = Line.Length;
                }
                if (entry != null)
                    entries.Push(entry);

                if (line == "End")
                {
                    if (entries.Count != 0)
                    {
                        FoldEntry endEntry = entries.Pop();
                        foldMarkers.Add(new FoldMarker(document, endEntry.Line, endEntry.Index, lineNumber, Line.Length));
                    }
                }

                lineNumber++;
            }
            return foldMarkers;
        }

        class FoldEntry
        {
            public int Line, Index;
        }
    }
}
